package com.kqkj.dyrule.marketing.querier;

import com.kqkj.dyrule.marketing.beans.EventBean;
import com.kqkj.dyrule.marketing.beans.EventCombinationCondition;
import com.kqkj.dyrule.marketing.beans.EventCondition;
import com.kqkj.dyrule.marketing.utils.EventUtil;
import org.apache.flink.api.common.state.ListState;

import java.util.List;

public class StateQuerier {
    ListState<EventBean> listBeans;
    public StateQuerier(ListState<EventBean> listState){
        this.listBeans = listState;
    }

    /**
     * state状态 根据组合条件及查询的时间范围，得到返回结果为213123形式的字符串序列
     * @param deviceId
     * @param eventCombinationCondition 行为组合条件
     * @param queryRangeStartTs 查询时间范围起始
     * @param queryRangeEndTs  查询时间范围结束
     * @return 用户做过的组合条件中的事件的字符串序列
     * 做过1,任意事件后做过3,任意事件后做过5
     */
    public String queryEventCombinationConditionStr(String deviceId, EventCombinationCondition eventCombinationCondition, long queryRangeStartTs, long queryRangeEndTs) throws Exception {
        Iterable<EventBean> eventBeans = listBeans.get(); //123465
        List<EventCondition> eventConditionList = eventCombinationCondition.getEventConditionList();
        StringBuffer sb = new StringBuffer();
        for (EventBean eventBean : eventBeans) {//135
            if (eventBean.getTimeStamp() <= queryRangeEndTs && eventBean.getTimeStamp() >= queryRangeStartTs){
                for (int i=0;i<eventConditionList.size();i++){
                    // 判断当前迭代到的bean，是否是条件中感兴趣的事件
                    boolean compare = EventUtil.compare(eventBean, eventConditionList.get(i));
                    if (compare) {
                        sb.append(eventConditionList.indexOf(eventBean));
                        break;
                    }
                }
            }
        }
        return sb.toString();
    }

    /**
     * state状态 根据组合条件及查询的时间范围，查询该组合出现的次数
     * @param deviceId
     * @param eventCombinationCondition 行为组合条件
     * @param queryRangeStartTs 查询时间范围起始
     * @param queryRangeEndTs  查询时间范围结束
     * @return
     */
    public int queryEventCombinationConditionCount(String deviceId, EventCombinationCondition eventCombinationCondition, long queryRangeStartTs, long queryRangeEndTs) throws Exception {
        //先查询用户在组合条件中做过的事件的字符串序列
        String eventSequenceStr = queryEventCombinationConditionStr(deviceId,eventCombinationCondition,queryRangeStartTs,queryRangeEndTs);
        //然后取出组合条件中的正则表达式
        String matchPattern = eventCombinationCondition.getMatchPattern();
        //正则匹配得到匹配的次数
        int count = EventUtil.sequenceStrMatchRegexGroupCount(eventSequenceStr, matchPattern);
        return count;
    }
}
